package cn.seventree.file.util;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 文件hash工具类
 *
 * @author cl
 * @date 2016-06-12
 * @since 1.0.0
 */
public class FileHashUtil {

    private FileHashUtil() {
    }

    /**
     * 校验文件内容hash值
     *
     * @param filePath 文件路径，绝对路径
     * @param hash     hash值
     * @return 通过则返回true, 否则返回false
     */
    public static final boolean checkFileHash(Path filePath, String hash) {
        String calculatedHash = calculateFileHash(filePath);
        if (StringUtils.isBlank(calculatedHash)) {
            return false;
        }

        return calculatedHash.equals(hash);
    }

    /**
     * 计算文件hash值
     *
     * @param filePath 文件路径
     * @return 计算的hash值，失败则返回null
     */
    public static final String calculateFileHash(Path filePath) {
        if (null == filePath || !Files.exists(filePath)) {
            return null;
        }
        MessageDigest sha1 = null;
        try {
            sha1 = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }

        byte[] buffer = new byte[4096];
        try (InputStream inputStream = Files.newInputStream(filePath)) {
            int readNum = 0;
            while (-1 < (readNum = inputStream.read(buffer, 0, buffer.length))) {
                sha1.update(buffer, 0, readNum);
            }

        } catch (IOException e) {
        }


        byte[] result = sha1.digest();
        return Hex.encodeHexString(result);
    }
}
